<?php
//include 'function.php';
//include 'FormProcessor/UserRegistration.php';

class AccountController extends Zend_Controller_Action
{
  private $db;
  private $user;
  public function init()
  {
    $db_obj = new myDb();
    $this->db = $db_obj->getDb();
    Zend_Db_Table::setDefaultAdapter($this->db);
  }

  public function indexAction()
  {
    $session = new Zend_Session_Namespace('account');
    if (isset($session->user) && $session->user->get("id") > 0)
      header('Location: /user');

    // action body
    $this->view->captcha_url = myCaptcha::create();
  }
  public function registerAction()
  {    
    $this->view->postRegisterData = $this->getRequest()->getParams();
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');

    if (isset($session->user) && $session->user->get("id") > 0)
      header('Location: /user');

    if ($this->getRequest()->isPost()) 
      {
	$formData = $this->getRequest()->getPost();
	/* check the captcha */
	$captcha_session = new Zend_Session_Namespace('captcha'); //在默认构造函数里实例化
	if ($captcha_session->phrase != $formData['captcha'])
	  {
	    $this->view->captcha_url = myCaptcha::create();
	    return $this->view->error = "验证码错误";
	  }

	if (empty($formData['username']))
	  {
	    $this->view->captcha_url = myCaptcha::create();
	    return $this->view->error = "用户名不能为空";
	  }
	if (strpos($formData['username'], '@'))
	  {
	    $user_field = 'email';
	  }
	else
	  {
	    $user_field = 'username';
	  }

	/* check whether user is already exists */
	$where = $this->db->quoteInto("$user_field = ?", $formData['username']);
	$user = new Application_Model_User();
	$usermapper = new Application_Model_UserMapper();
	$usermapper->findObj($where, $user);
	/* $user_table = new Application_Model_DbTable_User(); */

	/* if (count($user_table->fetchAll($where)) > 0) */
	if ($user && $user->get("id") > 0)
	  {
	    $this->view->captcha_url = myCaptcha::create();
	    $this->view->error = "此用户名已被使用";
	    /* print $this->view->error; */
	    return;
	  }

	$array = array($user_field=>$formData['username'],
		       /* 'nickName'=>$formData['nickname'], */
		       'password'=>md5($formData['password'])
		       );
	/* print_r($array); */
	$user->setOptions($array); /* = new Application_Model_User($array); */
	/* $usermapper = new Application_Model_UserMapper(); */
	if ($usermapper->save($user))
	  {
	    //if ($user_field == 'email')
	      //{
		/* send the confirmation email */

		/* show message prompt to active the email to continue */
		//header("Location: /account/registercomplete?type=email");
	      //}
	    //else
	      //{
		/* login automatical if username is given */
		Zend_Session::start();
		$session = new Zend_Session_Namespace('account');
		/* $session->user  = new Application_Model_User(); */
		/* $usermapper = new Application_Model_UserMapper(); */
		$usermapper->findObj($where, $user);
		$session->user = $user;

		/* print_r($session->user->getOptions()); */
		header("Location: /account/registercomplete?type=username");
	      //}
	  }
	else
	  {
	    $this->view->error = "注册失败，请稍候再试。";
	  }
	
	/* if ($fp->hasError()) */
	/*   $this->view->register_errors = $fp->getErrors(); */
      }
    $this->view->captcha_url = myCaptcha::create();
  }

  public function registercompleteAction()
  {
    if ($this->getRequest()->getParam('type')=='email')
      {
	$this->view->msg = "已经发送了一封电子邮件到您的注册邮箱中，请在您的邮箱中确认您的注册后继续。";
      }
    else if ($this->getRequest()->getParam('type')=='username')
      {
	$this->view->msg = "感谢您的注册，现在您已登录。<br/><a href='/user/profile'>完善个人信息<a/>&nbsp;&nbsp;<a href='/'>返回首页</a>";
      }
  }

  public function loginAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    if (isset($session->user) && $session->user->get("id") > 0)
      header('Location: /user');
    
    $message = '';

    if ($this->getRequest()->isPost())
      {
	$formData = $this->getRequest()->getParams();
	if (empty($formData['username']) || 
	    empty($formData['password']))
	  {
	    $message = '请填写用户名或密码';
	  }
	else
	  {
	    if (strpos($formData['username'], '@'))
	      $user_field = 'email';
	    else
	      $user_field = 'username';

	    // do the authentication
	    $authAdapter = new Zend_Auth_Adapter_DbTable($this->db,
							 'users',
							 $user_field,// 'email',//'username',
							 'password',
							 'md5(?)');
	    $authAdapter->setIdentity($formData['username']);
	    $authAdapter->setCredential($formData['password']);
	    $auth = Zend_Auth::getInstance();
	    $result = $auth->authenticate($authAdapter);

	    if ($result->isValid())
	      {
		$message = '登录成功';
		/* print $message; */

		$session->user  = new Application_Model_User();
		$usermapper = new Application_Model_UserMapper();
		$where = "$user_field = '{$formData['username']}'";
		$usermapper->findObj($where, $session->user);

		// remember me
		if (isset($formData['remember_me']) && $formData['remember_me'] == 'on')
		  {
		    setcookie('username', $formData['username'], time()+3600*24*7, "/");
		    setcookie('password', $formData['password'], time()+3600*24*7, "/");
		    setcookie('remember_me', $formData['remember_me'], time()+3600*24*7, "/");
		  }
		else
		  {
		    setcookie('username', "", time()-3600*24*7, "/");
		    setcookie('password', "", time()-3600*24*7, "/");
		    setcookie('remember_me', "", time()-3600*24*7, "/");
		  }

		header('Location: /user');
	      }
	    else
	      {
		switch ($result->getCode())
		  {
		  case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
		    $message = '用户名不存在';
		    break;
		  case Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS:
		    $message = '用户名不唯一';
		    break;
		  case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:		
		    $message = '密码错误';
		    // remember me
		    break;
		  default:
		    $message = '登录失败';
		    break;
		  }
	      }
	  }
	$this->view->login_user = $formData['username'];
	$this->view->login_passwd = $formData['password'];
	$this->view->login_error = $message;

      }

    $this->view->captcha_url = myCaptcha::create();
  }

  public function ajaxLoginAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    if (isset($session->user) && $session->user->get("id") > 0)
      {
	return $this->view->login = array('code'=>'0', 'message'=>'已成功登录');
      }
    $formData = $this->getRequest()->getParams();
    if (empty($formData['username']) || 
	empty($formData['password']))
      {
	$message = '请填写用户名或密码';
      }
    else
      {
	if (strpos($formData['username'], '@'))
	  $user_field = 'email';
	else
	  $user_field = 'username';

	// do the authentication
	$authAdapter = new Zend_Auth_Adapter_DbTable($this->db,
						     'users',
						     $user_field,// 'email',//'username',
						     'password',
						     'md5(?)');
	$authAdapter->setIdentity($formData['username']);
	$authAdapter->setCredential($formData['password']);
	$auth = Zend_Auth::getInstance();
	$result = $auth->authenticate($authAdapter);

	if ($result->isValid())
	  {
	    $message = '登录成功';
	    //print $message;

	    $session->user = new Application_Model_User();
	    $usermapper = new Application_Model_UserMapper();
	    $where = "$user_field = '{$formData['username']}'";
	    $usermapper->findObj($where, $session->user);

	    // remember me
	    if (isset($formData['remember_me']) && $formData['remember_me'] == 'on')
	      {
		$message .= ";;remember me, ser username and password in cookie;;";
		setcookie('username', $formData['username'], time()+3600*24*7, "/");
		setcookie('password', $formData['password'], time()+3600*24*7, "/");
		setcookie('remember_me', $formData['remember_me'], time()+3600*24*7, "/");
	      }
	    else
	      {
		$message .= ";;not remember me, clear cookie;;";
		setcookie('username', "", time()-3600*24*7, "/");
		setcookie('password', "", time()-3600*24*7, "/");
		setcookie('remember_me', "", time()-3600*24*7, "/");
	      }

	    //header('Location: /user');
	    $this->view->login = array('code' => '0', 'message' => $message, 'user' => $formData['username']);
	  }
	else
	  {
	    switch ($result->getCode())
	      {
	      case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
		$message = '用户名不存在';
		break;
	      case Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS:
		$message = '用户名不唯一';
		break;
	      case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:		
		$message = '密码错误';
		break;
	      default:
		$message = '登录失败';
		break;
	      }
	    $this->view->login = array('code' => $result->getCode(), 'message' => $message);
	  }
      }

  }
  public function logoutAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    $session->unsetAll();

    $this->view->captcha_url = myCaptcha::create();
    header('Loaction: /account');
  }
}

